<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryForm" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryForm.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 180px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="queryForm.phone"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 180px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryForm.status"
              placeholder="请输入用户状态"
              clearable
              size="small"
              style="width: 180px"
            >
              <el-option :value="0" :key="0" :label="'启用'"></el-option>
              <el-option :value="1" :key="1" :label="'禁用'"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-has-perm="['system_user:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdate"
              :disabled="single"
              v-has-perm="['system_user:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
              :disabled="multiple"
              v-has-perm="['system_user:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click=""
              v-has-perm="['system_user:import']"
            >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click=""
              v-has-perm="['system_user:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="handleQuery"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="用户编号" align="center" prop="id"/>
          <el-table-column label="用户名称" align="center" prop="userName" show-overflow-tooltip/>
          <el-table-column label="登录账号" align="center" prop="loginName" show-overflow-tooltip/>
          <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip/>
          <el-table-column label="角色" align="center" prop="roleName" show-overflow-tooltip/>
          <el-table-column label="手机号码" align="center" prop="phone" width="120"/>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="detail"
                icon="el-icon-view"
                @click="handleUpdate(scope.row)"
                v-has-perm="['system_user:detail']"
              >详情
              </el-button>
              <el-button
                v-if="scope.row.level !== 1"
                size="mini"
                type="del"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-has-perm="['system_user:remove']"
              >删除
              </el-button>
              <el-button
                size="mini"
                type="grey"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                v-has-perm="['system_user:resetPwd']"
              >重置
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryForm.cursor"
          :limit.sync="queryForm.limit"
          @pagination="_getUser"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-dialog-drag :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="userForm" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户昵称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId"
                          :options="deptOptions"
                          :show-count="true"
                          :normalizer="$normalizer"
                          placeholder="请选择归属部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="用户名称" prop="loginName">
              <el-input v-model="form.loginName" placeholder="请输入用户名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="item in sexOptions" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleId" placeholder="请选择" clearable>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.status == 1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <span v-has-perm="['system_user:add']">
          <el-button type="primary" v-if="title=='添加用户'" @click="submitForm">确 定
          </el-button>
        </span>
        <span v-has-perm="['system_user:edit']">
          <el-button type="primary" v-if="title=='修改用户'" @click="submitForm">确 定
          </el-button>
        </span>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addUser, changeUserStatus, delUser, getUser, getUserById, resetUserPwd, updateUser} from "@/api/system/user";
import {getRoleList} from '@/api/system/role'
import {getDeptTrees} from '@/api/system/dept'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询表单数据对象
      queryForm: {
        username: undefined,
        roleId: undefined,
        status: undefined,
        cursor: 1,
        limit: 20
      },
      // 总条数
      total: 0,
      userList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      //用户模块
      form: {
        id: undefined,
        deptId: undefined,
        userName: undefined,
        loginName: undefined,
        password: undefined,
        phone: undefined,
        email: undefined,
        sex: undefined,
        status: 0,
        remark: undefined,
        roleId: undefined
      },
      open: false,
      title: '',
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"}
        ],
        loginName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"}
        ],
        email: [
          {type: "email", message: "'请输入正确的邮箱地址", trigger: ["blur", "change"]}
        ],
        phone: [
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      },
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 角色选择数据
      roleOptions: [],
      // 性别选项
      sexOptions: [{value: 0, label: "男"}, {value: 1, label: "女"}],
    }
  },
  methods: {
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryForm.deptId = data.id;
      this.handleQuery();
    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      getDeptTrees().then(({result: res}) => {
        this.deptOptions = res;
      })
    },
    // 获取职位列表
    getRoleList() {
      // 发起请求
      getRoleList().then(({result: res}) => {
        this.roleOptions = res
      })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryForm.cursor = 1
      this._getUser()
    },
    // 获取用户列表
    _getUser() {
      getUser(this.queryForm).then(({result: res}) => {
        this.total = res.total
        this.userList = res.records
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm.deptId = undefined
      this.resetForm("queryForm")
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form
      this.resetForm("form");
    },
    // 用户状态修改
    async handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "停用";
      const confirm = await this.$confirm('确认要' + text + ' "  ' + row.userName + '  " 用户吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err)
      if (confirm != 'confirm') {
        row.status = row.status === 0 ? 1 : 0
        return this.$message.info('取消操作')
      }
      changeUserStatus(row.id, row.status).then((res) => {
        this.$message.success(text + "成功");
      }).catch(err => {
        row.status = row.status === 0 ? 1 : 0
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入 "  ' + row.userName + '  " 的新密码', "重置密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password"
      }).then(({value}) => {
        resetUserPwd(row.id, value).then(res => {
          this.$message.success("修改成功，新密码是：" + value);
        })
      }).catch(() => {
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeSelect();
      this.title = "添加用户";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeSelect();
      const userId = row.id || this.ids;
      getUserById(userId).then(({result: res}) => {
        this.form = res;
        this.title = "修改用户";
        this.open = true;
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      if (!this.validForm("form")) {
        return
      }
      if (this.form.id != undefined) {
        updateUser(this.form).then(res => {
          this.$message.success("修改成功");
          this.open = false;
          this.handleQuery();
        })
      } else {
        addUser(this.form).then(res => {
          this.$message.success("新增成功");
          this.open = false;
          this.handleQuery();
        })
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const userIds = row.id || this.ids;
      const confirm = await this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err)

      if (confirm != 'confirm') {
        return this.$message.info('取消操作')
      }
      delUser(userIds).then((res) => {
        this.handleQuery();
        this.$message.success("删除成功");
      })
    },
  },
  created() {
    this.handleQuery();
    this.getTreeSelect();
    this.getRoleList()
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
}
</script>

<style scoped>

</style>
